import com.base.common.datesource.MultipleDataSource;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.*;
import com.base.common.persistent.query.TNewsQuery;
import com.base.common.persistent.query.TShopsQuery;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * Created by Kevin on 2017-9-18.
 */

@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试  
@ContextConfiguration({"/spring.xml", "/spring-mybatis.xml"}) //加载配置文件  
public class MoveShopData {

    String uploadPath = "http://120.25.120.99:9999/upload";

    @Resource
    private TShopsMapper tShopsMapper;

    @Resource
    private TShopMapper tShopMapper;

    @Resource
    private TUserMapper tUserMapper;

    @Resource
    private TUserRoleMapper tUserRoleMapper;

    @Resource
    private TNewsMapper tNewsMapper;

    @Resource
    private TItemMapper tItemMapper;

    @Test
    public void test() {

    	
            MultipleDataSource.setDataSourceKey("cjyShopDataSource");
            TShopExample tShopExample = new TShopExample();
            tShopExample.createCriteria();
            List<TShop> shops = new ArrayList<>();
            	shops = tShopMapper.selectByExample(tShopExample);
            
        	List<TUser> users = tUserMapper.selectByExample(new TUserExample());
            MultipleDataSource.setDataSourceKey("shopDataSource");
            for (TUser user : users) {
            	List<TShops> tShops = tShopsMapper.selectByCuname(user.getUserPhone());
            	for (TShops shop : tShops) {
            		TNewsQuery tNewsQuery = new TNewsQuery();
                    tNewsQuery.setCtypeB(shop.getcId());
                    List<TNews> newses = tNewsMapper.selectObjectByCondition(tNewsQuery);
                    
                    for (TNews news : newses) {
                    	String itemName = news.getTitles();
                        int itemSeq = 0;
                        int itemStocks = 999999999;
                        int itemStatus = 0;
                        long itemCategoryId = 0;
                        String itemUuid = UUID.randomUUID().toString();
                        String itemImgUrl = "";
                        BigDecimal itemPrice = BigDecimal.valueOf(news.getPrice());
                        String itemDesc = "";
                        List<TShop> list = shops.stream().filter(s -> s.getShopName().equals(shop.getcSname())).collect(Collectors.toList());
                        if(list.size() > 0) {
                        	long shopId = list.get(0).getShopId();

                            if(news.getContents().contains("src")) {
                                String picUrl = "http://120.25.120.99:2222" + news.getContents()
                                        .substring(news.getContents().indexOf("src")
                                                + 5, news.getContents().substring(news.getContents()
                                                .indexOf("src") + 5).indexOf("\"") + (news.getContents().indexOf("src") + 5));
                                try {
                                    itemImgUrl = uploadFileOnline(picUrl.substring(picUrl.lastIndexOf("/") + 1), picUrl);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }

                            Document document = Jsoup.parse("");
                            document.append(news.getContents());
                            Elements imgs = document.getElementsByTag("img");
                            imgs.stream().forEach((img) -> {
                                String src = img.attr("src");
                                src = "http://120.25.120.99:2222" + src;
                                try {
                                    src = uploadFileOnline(src.substring(src.lastIndexOf("/") + 1), src);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                img.attr("src", src);
                            });
                            document.getElementsByTag("html").remove();
                            itemDesc = document.toString().trim();

                            TItem tItem = new TItem();
                            tItem.setItemCategoryId(itemCategoryId);
                            tItem.setItemName(itemName);
                            tItem.setItemSeq(itemSeq);
                            tItem.setItemStocks(itemStocks);
                            tItem.setItemStatus(itemStatus);
                            tItem.setItemUuid(itemUuid);
                            tItem.setImgUrl(itemImgUrl);
                            tItem.setItemDesc(itemDesc);
                            tItem.setItemPrice(itemPrice);
                            tItem.setShopId(shopId);
                            MultipleDataSource.setDataSourceKey("cjyShopDataSource");
                            try {
                            tItemMapper.insertSelective(tItem);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            MultipleDataSource.setDataSourceKey("shopDataSource");
                        }
                        
					}
				}
			}
    	
            	
    }

    private String uploadFileOnline(String fileName, String fileUrl) throws IOException {
    	System.out.println("开始上传");
        URL url = new URL(fileUrl);
        URLConnection urlConnection = url.openConnection();
        InputStream is = urlConnection.getInputStream();
        urlConnection.setDefaultUseCaches(false);

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setBufferRequestBody(false);
        RestTemplate rest = new RestTemplate(requestFactory);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2048];
        while (is.read(buffer) > 0) {
            bos.write(buffer);
        }
        bos.flush();
        is.close();
        bos.close();
        ByteArrayResource arrayResource = new ByteArrayResource(bos.toByteArray()){
            @Override
            public String getFilename() throws IllegalStateException {
                return fileName;
            }

        };
        param.add("file", arrayResource);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param);
        return rest.exchange(uploadPath, HttpMethod.POST, httpEntity, String.class).getBody();
    }

}
